import { ref, watch } from "vue";
export function useResponseHook(getProps, extra = {}) {
  const listData = ref([]);
  const loading = ref(false);
  const rowTotal = ref(0);
  const currentPage = ref(1);
  const curPageSize = ref(getProps.pageSize?.value || 10);

  async function load(page = currentPage.value) {
    loading.value = true;
    try {
      const res = await getProps.fetcher.value({
        page,
        pageSize: curPageSize.value,
        filters: getProps.filters.value,
      });
      listData.value = res.list || [];
      rowTotal.value = res.total || 0;
      extra.onSuccess && extra.onSuccess(listData.value);
    } catch (e) {
      extra.onError && extra.onError(e);
    } finally {
      loading.value = false;
    }
  }

  function search() {
    currentPage.value = 1;
    load(1);
  }

  function refresh() {
    load();
  }

  function setPageSize(size) {
    curPageSize.value = size;
  }

  // 监听 filters 改变
  watch(getProps.filters, () => search(), { deep: true });

  // 首次加载
  if (getProps.autoLoad.value) {
    load();
  }

  return {
    listData,
    loading,
    rowTotal,
    currentPage,
    curPageSize,
    search,
    refresh,
    setPageSize,
    load,
  };
}
